package sysmessage

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"log"
	"net/url"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/websocket"
)

const chunkSize = 1024

func setClient() {
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	url := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"}
	conn, _, err := websocket.DefaultDialer.Dial(url.String(), nil)
	if err != nil {
		log.Fatal("WebSocket connection error:", err)
	}
	defer conn.Close()

	// 读取本地图片文件
	file, err := os.Open("example.jpg")
	if err != nil {
		log.Fatal("Failed to open image file:", err)
	}
	defer file.Close()

	buffer := new(bytes.Buffer)
	_, err = buffer.ReadFrom(file)
	if err != nil {
		log.Fatal("Failed to read image file:", err)
	}

	// 压缩图片数据
	compressedBuffer := new(bytes.Buffer)
	gzipWriter := gzip.NewWriter(compressedBuffer)
	_, err = io.Copy(gzipWriter, buffer)
	if err != nil {
		log.Fatal("Failed to compress image data:", err)
	}
	gzipWriter.Close()

	// 分片发送图片数据
	imageData := compressedBuffer.Bytes()
	numChunks := len(imageData) / chunkSize
	lastChunkSize := len(imageData) % chunkSize
	for i := 0; i < numChunks; i++ {
		chunk := imageData[i*chunkSize : (i+1)*chunkSize]
		err := conn.WriteMessage(websocket.BinaryMessage, chunk)
		if err != nil {
			log.Println("Failed to send chunk:", err)
			return
		}
	}

	// 发送剩余的最后一个分片
	if lastChunkSize > 0 {
		lastChunk := imageData[numChunks*chunkSize:]
		err := conn.WriteMessage(websocket.BinaryMessage, lastChunk)
		if err != nil {
			log.Println("Failed to send last chunk:", err)
			return
		}
	}

	// 等待接收确认消息
	_, message, err := conn.ReadMessage()
	if err != nil {
		log.Println("Failed to receive confirmation message:", err)
		return
	}
	fmt.Printf("Received confirmation message from server: %s\n", message)

	// 等待一段时间
	time.Sleep(3 * time.Second)
}
